package authoritah.ui.event;

import java.awt.event.ActionEvent;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.text.BadLocationException;

import authoritah.db.Attendance;
import authoritah.db.Event;
import authoritah.db.Member;
import authoritah.utils.TimeUtils;


public class EventAttendanceController {
	private EventAttendanceView view;
	private EventAttendanceModel model;
	
	public EventAttendanceController() {
		model = new EventAttendanceModel();
		view = new EventAttendanceView(model);
		
		createAndAssignActions();
	}
	
	private void createAndAssignActions() {
		Action parseAction = new AbstractAction("Parse entered data") {
			public void actionPerformed(ActionEvent e) {
				if (model.getCopyPasteDocument().getLength() > 0) {
					ArrayList<Attendance> attendanceList = new ArrayList<Attendance>();
					try {
						String originalData = model.getCopyPasteDocument().getText(0, model.getCopyPasteDocument().getLength());
						String[] lines = originalData.split("\n");
						for (String line : lines) {
							String[] data = line.split(" ");
							Attendance attendance = new Attendance();
							attendance.setMember(Member.getMember(data[0])); // TODO fix method so it looks up similar names and guesses at one
							
							if (data.length > 1) {
								attendance.setArrive(TimeUtils.parseTime(data[1]));
							}
							else {
								attendance.setArrive(model.getStart());
							}
							
							if (data.length > 2) {								
								attendance.setLeave(TimeUtils.parseTime(data[2]));
							}
							else {
								attendance.setLeave(model.getEnd());
							}
							
							attendanceList.add(attendance);
						}
					} catch (BadLocationException error) {
						error.printStackTrace();
					}
					model.getInputTableModel().updateData(attendanceList);
				}
				else {
					JOptionPane.showMessageDialog(view, "Enter some data to parse");
				}
			}
		};
		view.setParseAction(parseAction);
		
		Action saveAttendanceAction = new AbstractAction("Save Attendance") {

			public void actionPerformed(ActionEvent e) {
				Event event = new Event();
				event.setStart(model.getStart());
				event.setEnd(model.getEnd());
				event.setMaxPoints(model.getMaxPoints());
				event.setEventType(model.getSelectedEventType());
				event.setName(model.getEventName());
				Event.saveEvent(event);
				event = Event.getEvent(event.getStart(), event.getEnd());
				
				for (Attendance attendance : model.getAttendanceList()) {
					attendance.setEvent(event);
					Attendance.saveAttendance(attendance);
				}
			}
			
		};
		view.setSaveAction(saveAttendanceAction);
	}

	public JPanel getDisplayComponent() {
		return view;
	}
}
